package com.onemore.task.location;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.voovan.tools.log.Logger;

import com.alibaba.druid.support.json.JSONParser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.response.handle.StringDataHandler;
import com.onemore.task.OneJdbc;
import com.onemore.task.QimenSign;
import com.onemore.task.model.ModelJsend;
import com.onemore.task.model.ModelJsendmx;
import com.onemore.task.model.ModelJtsqd;
import com.onemore.task.model.ModelSpthd;

public class LocTaskSpthd extends LocTaskBase{
	public static void process(String DJBH,String stamp) throws SQLException, InterruptedException
	{	
		int ret=0;
		List<Map<String, Object>> listSpthd = null; 
		List<Map<String, Object>> listSpthdmx = null; 
		String YDJH = null; 
		listSpthd = OneJdbc.getSpthd(DJBH);
		if(listSpthd.size() == 0)throw new SQLException("没有找到对应单号的退货单，DJBH:"+DJBH);
		//等等此表同步完成
		Thread.sleep(10);
		listSpthdmx = OneJdbc.getSpthdmx(DJBH);
		String LXDJ = (String)listSpthd.get(0).get("LXDJ");//申请单号
		if(LXDJ == null || LXDJ.length() == 0)throw new SQLException("退货单找不到对应的退货申请单，单据编号（DJBH）："+DJBH+"，LXDJ："+LXDJ);
		YDJH = ModelJtsqd.getYdjh(LXDJ);
		if(YDJH == null) {
			Logger.error("此退货通知单单号为空，可能与SCM无关，自动被忽略 单据编号（DJBH）:"+DJBH);
			OneJdbc.deleteMtab(stamp);
			return;
		}
		if(!ModelJsend.isExist(YDJH)) {
			Logger.error("此通知单单号异常，无法找到对应的采购通知单，退货单单据编号："+DJBH+",通知单单号（YDJH）："+YDJH);
			OneJdbc.deleteMtab(stamp);
			return;
		}

		if(!ModelJsendmx.isExist(YDJH)) {
			Logger.error("采购通知单主表的对应的明细表数据为空，不符合SCM规范，此数据自动被忽略");
			OneJdbc.deleteMtab(stamp);
			return;
		}
		if(listSpthd != null && listSpthd.size() > 0) {
			listSpthd.get(0).put("items", listSpthdmx);
			ret = LocTaskSpthd.postHttpForSpthdInsert(listSpthd,listSpthdmx,YDJH);				            				
			//if(ret == 0 || ret == 200) 
			{
//				ModelSpthd.updateFlag(DJBH);
				if(OneJdbc.deleteMtab(stamp)) {
					
				}
			}
		}else {
			Logger.error("未找到退货单数据");
			OneJdbc.deleteMtab(stamp);
		}
	}
	/**
	 * 商品退货数据提交给SCM系统
	 * @param spthd
	 * @return
	 * @serialData insert into ONE_MTAB (KEY_VALUE,ACT_TYPE,TAB_NAME) values('JA6120320000003','SPTHD','insert');
	 */
	public static int postHttpForSpthdInsert(JSONObject spthd)
	{
		int ret=0;
		String url = "/test/R/RestHandle.ashx";//scm
		url += "?method=scm.160240.rkd.th";
		url += "&timestamp="+df.format(new Date());
		url += "&format=json";
		url += "&app_key=scm.om.bs";
		url += "&v=2.0";
		url += "&sign_method=md5";
		url += "&customerId=onemore";
		String body = spthd.toJSONString();
        QimenSign sign = new QimenSign();
        String md5 = sign.sign(url, body, secretKey);
		url += "&sign="+md5;
		outer:do {

			Logger.info("SCM发送退货单链接："+(host+url)+"\r\n Body:"+body);
			com.mzlion.easyokhttp.response.HttpResponse httpResponse = com.mzlion.easyokhttp.HttpClient.textBody(host+url)
	                .text(body)
	                .charset(charset)
	                .execute();
	        String asString = httpResponse.custom(StringDataHandler.create(), false);
	        if(httpResponse.getHttpCode() == 200) {
	        	if(asString != null && asString != "") {
			        JSONParser parse =new JSONParser(asString);  //创建json解析器
			        JSONObject jsonObject= new JSONObject(parse.parseMap());
			        /*if(jsonObject.getInteger("code") == 200) {
			        	break outer;
			        }*/
			        ret = jsonObject.getInteger("code");
	        	}else {
	        		ret = -450;
	        	}
	        }else {
	        	ret = -451;
	        }
	        if(ret == 200) {
				Logger.info("成功同步一条退货数据:"+asString);
	        }else
	        if(httpResponse.getHttpCode() != 200) {
	        	Logger.error("商品退货失败 http返回 code = "+httpResponse.getHttpCode()+" 错误消息："+httpResponse.getErrorMessage());
	        }else
	        if(ret != 200) {
	        	Logger.error("商品退货服务器请求失败 报文："+asString+"\r\n请求报文："+body);
	        }
		}while(false);
		return ret;
	}
	public static int postHttpForSpthdInsert(List<Map<String,Object>> listSpthd, List<Map<String,Object>> listSpthdmx,String YDJH) throws SQLException
	{
		JSONObject jsonObject = readyDataToSPTHD(listSpthd, listSpthdmx,YDJH);
		if(jsonObject == null) {
			return 0;
		}else
			return postHttpForSpthdInsert(jsonObject);
	}
	/**
     * 将退货单的数据库查询到的数据转化为报文json格式
     * @param json
     * @return
	 * @throws SQLException 
     */
	public static JSONObject readyDataToSPTHD(List<Map<String,Object>> listSpthd, List<Map<String,Object>> listSpthdmx,String jsendBh) throws SQLException
	{
		int state = 0;
		int itemCnt = 0;
		Map<String, JSONArray> skusmap = new HashMap<String,JSONArray>();
		Map<String,Object> spthdMap = listSpthd.get(0);
		JSONObject scmJsonObject = new JSONObject();
		//String jsendBh = (String)spthdMap.get("LXDJ");//通知单单号 原BYZD3
		if(jsendBh == null) {
			Logger.warn("数据库对应的退货通知单号为空，此条数据无效，无法发送，所以无法发送。单据编号:"+spthdMap.get("DJBH"));
			return null;
		}
		scmJsonObject.put("sdh", jsendBh);//SCM入库通知单单号
		scmJsonObject.put("wdh", spthdMap.get("DJBH"));//WMS次品退厂单单号 
		scmJsonObject.put("sm", spthdMap.get("BZ"));//备注
		String ywy = null;
		if(spthdMap.containsKey("JZR"))
			ywy = (String)spthdMap.get("JZR");
		if(ywy == null)ywy = "undefined";
		scmJsonObject.put("_su", ywy);//维护用户名
		scmJsonObject.put("_st", df.format(new Date()));//维护用户名
		JSONArray itemsArray = new JSONArray();
		
		for(int i=0;i<listSpthdmx.size();i++) {
			Map<String,Object> spthdmxMap = listSpthdmx.get(i);
			String gg1dm = (String)spthdmxMap.get("GG1DM");
			String chima = (String)spthdmxMap.get("GG2DM");
			String SPDM = (String)spthdmxMap.get("SPDM");
			String PKID = null;
			try {
				PKID = ModelJsendmx.getPkidFromJsendmx(jsendBh,gg1dm,SPDM);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				Logger.error(e);
				continue;
			}
			if(PKID == null) {
				state = -1;
				Logger.warn("在同步商品退货单时，获取到的商品的PKID为空,通知单号（jsendBh）："+jsendBh+" 颜色代码："+gg1dm+" 商品代码："+SPDM);
				continue;
			}
			JSONObject skuObject = new JSONObject();
			skuObject.put("sku", spthdmxMap.get("SPDM")+gg1dm+chima);
			skuObject.put("qty", spthdmxMap.get("SL"));//入库数	
			
			//生成归类
			JSONArray tmpAry = skusmap.get(PKID);
			if(tmpAry == null) {
				tmpAry = new JSONArray();
				skusmap.put(PKID,tmpAry);
			}
			tmpAry.add(skuObject);
			itemCnt ++;
		}
		if(itemCnt == 0) {
			Logger.error("退货单的商品信息与SCM通知单的商品信息不能对应，此数据自动被忽略,JSON:"+scmJsonObject.toJSONString());
			return null;
		}
		for (Map.Entry<String, JSONArray> entry : skusmap.entrySet()) {
			JSONObject itemObject = new JSONObject();
			itemObject.put("pkid", entry.getKey());
			itemObject.put("skus", entry.getValue());
			itemsArray.add(itemObject);
		}  
		scmJsonObject.put("items", itemsArray);
		if(itemCnt < ModelJsendmx.getCount(jsendBh)) {
			Logger.warn("退货商品数量少于通知单商品数量"+scmJsonObject.toJSONString());
		}
		return scmJsonObject;
	}
}
